//
//  BookSortViewModel.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 04.04.25.
//

import Foundation
class BookSortViewModel : KoiAccountingBaseViewModel {
    
    private let bookDao = KoiAccountingDB.standard.getBookDao()
    
    @Published var sortState = ""
    
    @Published var books = Array<AccountingBook>()
    
    func loadBooks() {
        asyncBackground {
            let result = self.bookDao.getAllBook(uid: self.uid)
            self.asyncMain {
                self.books = result.filter{ item in !item.isDefaultBook() }
            }
        }
    }
    
    func updateBookOrder(from source: IndexSet, to destination: Int) {
        // 获取移动范围的起始和结束位置
        let start = source.min()!
        let end = destination > start ? destination - 1 : destination

        // 更新起始和结束位置之间的 orderId
        var updateBooks = books[min(start, end)...max(start, end)]
        for index in updateBooks.indices {
            updateBooks[index].orderId = index + 1
        }
        asyncBackground {
            self.bookDao.update(books: Array(updateBooks))
            self.asyncMain {
                self.sortState = "success"
            }
        }
    }
}
